import multiprocessing
import sys
import time
from multiprocessing import Process


def daemon_proc():
    """
    守护进程
    :return:
    """
    p = multiprocessing.current_process()
    print("Starting..", p.name, p.pid)
    sys.stdout.flush()
    time.sleep(10)
    print("Exiting..", p.name, p.pid)
    sys.stdout.flush()


def no_daemon_proc():
    """
    非守护进程
    :return:
    """
    p = multiprocessing.current_process()
    print("Starting..", p.name, p.pid)
    sys.stdout.flush()
    print("Exiting..", p.name, p.pid)
    sys.stdout.flush()


if __name__ == "__main__":
    curr_proc = multiprocessing.current_process()
    print("主进程:", curr_proc.name, curr_proc.pid)
    d = Process(target=daemon_proc, name="daemon")
    nd = Process(target=no_daemon_proc, name="non_daemon")
    d.daemon = True
    nd.daemon = False
    d.start()
    time.sleep(2)
    nd.start()
    nd.join()
    # d.join()
    d.join(2) # 等待超时后，自动返回
    print("主程序执行完毕")
